package pl.myszon.RILLib;

import java.util.Map;

/**
 *
 * @author Myszon
 */
public class Connection {

    Config config = null;
    Connection(Config config) {
        this.config = config;
    }

    boolean isAuthenticationSuccessful() throws ConnectionFailureException {
        Request req = new AuthRequest();
        Response results = sendRequest(req);
        ResponseParser parser = new ResponseParser();
        ServerAnswer<Object> answer = parser.parse(results);

        if(answer.status == StatusCode.OK)
            return true;
        else
            return false;
    }

    Response getStatus() throws ConnectionFailureException {
        Request req = new StatusRequest();
        Response results = sendRequest(req);

        return results;
    }

    Response addLink(Website website) throws ConnectionFailureException {
        AddWebsiteRequest req = new AddWebsiteRequest();
        req.setWebsite(website);
        Response results = sendRequest(req);

        return results;
    }


    private Response sendRequest(Request request) throws ConnectionFailureException {
        request.setConfiguration(config);
        String connectionUrl = request.getRequestURL();

        HTTPSConnectionHandler connection = new HTTPSConnectionHandler(config, connectionUrl);
        Map header = connection.getHeader();
        String content = connection.getContent();

        return new Response(content, header);
    }

    private boolean isConfigNotNull() {
        if(config == null)
            return false;
        else
            return true;
    }




}
